<?php
class jQueryCascade extends CWidget
{
    private $baseUrl;

    public function init()
    {
        $assets = dirname(__FILE__) . '/js';
        $this->baseUrl = Yii::app()->getAssetManager()->publish($assets);
        $this->registerClientScript();

        parent::init();
    }

    protected function registerClientScript()
    {
        $js = $this->baseUrl . '/jquery.cascade-select.js';
        Yii::app()->clientScript->registerCoreScript('jquery');
        Yii::app()->clientScript->registerScriptFile($js);
    }

    public function dropDownList($id, $selected, $data, $htmlOptions = array(), $source, $cascaded, $callback = '')
    {
    	if(is_array($cascaded))
    	{
    		$i=0;
    		$script = "$('#" . $idDDL . "')";
    		foreach($cascaded as $c)
    		{
    			$script .= ".cascade({source:'" . $source[$i++] . "',cascaded:'" . $c . "', callback:'".$callback."'})";
    		}
    	}
    	else
    	{
	        $script = "$('#" . $id . "').cascade({source:'" . $source . "',cascaded:'" . $cascaded . "', callback:'".$callback."'})";
	        //Yii::app()->clientScript->registerScript('jQueryCascade' . $id, $script, CClientScript::POS_READY);
    	}
    	Yii::app()->clientScript->registerScript('jQueryCascade_' . $attribute, $script.".act();", CClientScript::POS_READY);
        return CHtml::dropDownList($id, $selected, $data, $htmlOptions);
    }

	public function activeDropDownList($model, $attribute, $data, $htmlOptions = array(), $source, $cascaded, $callback = '')
    {
    	$idDDL = get_class($model). "_" . $attribute;
    	if(isset($htmlOptions['id'])) $idDDL = $htmlOptions['id'];

    	if(is_array($cascaded))
    	{
    		$i=0;
    		$script = "$('#" . $idDDL . "')";
    		foreach ($cascaded as $c)
    		{
    			$script .= ".cascade({source:'" . $source[$i++] . "', cascaded:'" . $c . "', callback:'".$callback."'})";
	        	//break;
    		}
    	}
    	else
    	{
	        $script = "$('#" . $idDDL . "').cascade({source:'" . $source . "', cascaded:'" . $cascaded . "', callback:'".$callback."'})";
    	}
    	Yii::app()->clientScript->registerScript('jQueryCascade_' . $attribute, $script.".act();", CClientScript::POS_READY);
        return CHtml::activeDropDownList($model, $attribute, $data, $htmlOptions);
    }
}
